<?
	require('common.php');
	$att_path = "banners/";

	loadBanner();

	function loadBanner(){
		$result = @mysql_query("select id FROM banners WHERE pos='' LIMIT 1");
		if(mysql_num_rows($result) == 0) { 
			@mysql_query("UPDATE banners SET pos='' WHERE pos='A'"); 
		}
		$res = mysql_query("SELECT id FROM banners WHERE pos='' ORDER BY id LIMIT 1");
		if ( ($res) && (mysql_num_rows($res) > 0) ){
			$row = mysql_fetch_array($res);
			if ($row){
				extract( $row );
				if ($id){
					viewBanner($id);
				}
			}
		}
	}
	function viewBanner($id){
		global $siteurl,$att_path,$b_height,$b_width;
		if($b_width){
			$imgstr = " width=$b_width";
		}
		if($b_height){
			$imgstr .= " height=$b_height";
		}
		
		$query = "SELECT html, date FROM banners WHERE id = $id";
		$result = @mysql_query($query) or die( $query."<br>".mysql_error() );
		if($row = mysql_fetch_object($result) ){
			// Increment the numImps field for this banner
			@mysql_query("UPDATE banners SET pos='A', numImps = numImps + 1 WHERE id = $id") or die( mysql_error() );
			// Output the JavaScript and the images
			$handle=opendir($att_path); 
			while (false!==($file = readdir($handle))) { 
				if ($file != "." && $file != "..") { 
					if( strstr($file , "xban".$id."_") ){
						$furl = $siteurl.(str_replace("./","",$att_path))."/".$file;
?>
						document.write('<a target="_blank" href="<?=$siteurl?>/track.php?id=<?= $id; ?>&img=top">');
						document.write('<img src="<?=$furl?>" border=0 <?=$imgstr?>>');
						document.write('</a>');
<?
					}
				} 
			}
			closedir($handle); 
		}else{
			loadBanner();
		}
	}
?>